/*
 * @(#)FormDBlookupDAObject.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */

package com.dcivision.form.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.dcivision.form.bean.FormDBlookupSQL;
import com.dcivision.framework.DataSourceFactory;
import com.dcivision.framework.Utility;

/**
FormDBlookupDAObject.java

This class is the data access bean for DB lookup function.

@author      Charlie liu
@company     DCIVision Limited
@creation date   12/09/2006
@version     $Revision: 1.1.26.2 $
*/

public class FormDBlookupDAObject{
	
  public static final String REVISION = "$Revision: 1.1.26.2 $";
  
  protected Log log = LogFactory.getLog(this.getClass().getName());
  
  private Connection con;
  
  public FormDBlookupDAObject(){
  	super();
  }

  public FormDBlookupDAObject(Connection dbConn) {
    super();
    this.con=dbConn;
  }
  private Connection getDBConnection() throws Exception{
  	if(this.con!=null){
  		return con;
  	}else{  		
  			con=DataSourceFactory.getConnection();
  			return con;
  	}
  }
  public List getList(FormDBlookupSQL sql) {
    PreparedStatement sqlStatement = null;
    String sqlStr=null;
    ResultSet rs = null;
    List result = new ArrayList();
  	try{
  		getDBConnection();
  		if(Utility.isEmpty(sql.getCondition().trim())){
  			sqlStr="select "+sql.getField()+" from "+sql.getTable();
  		}else{
  			sqlStr="select "+sql.getField()+" from "+sql.getTable()+" where "+sql.getCondition();
  		}  		
  		log.debug("SQL statement: "+sqlStr);
  		sqlStatement=con.prepareStatement(sqlStr);
  		rs=sqlStatement.executeQuery();
  		String value=new String();
     	while(rs.next()){            
        value=rs.getString(1);
        log.debug("value=: "+value);
        result.add(value);
      }if(result==null||result.isEmpty()){
    	  log.debug("Record not found");
      }
  	}catch(Exception e){
      log.error(e, e);         
    }finally{
    	try {
    		if(rs != null) {
          rs.close();
        }
        if(con!=null) {
          con.close();
        }    
      }catch (SQLException e) {
        log.error(e, e);
       throw new RuntimeException("error.unexpecte");
     }
   }
    return result;
 }
}  
